package com.mr.security.web.commons.config;

import com.mr.security.web.commons.filter.SmsCodeAuthenticationFilter;
import com.mr.security.web.commons.mobile.SmsCodeAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * Class: SmsCodeAuthenticationSerurityConfig
 * User (作者):MRui
 * TODO (描述)：手机短信验证安全配置
 * Date 2019-01-26 22:24
 */
@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    /** 失败处理器 */
    @Autowired
    private AuthenticationFailureHandler failureHandler;
    /** 成功处理器*/
    @Autowired
    private AuthenticationSuccessHandler successHandler;
    /** 读取用户信息 */
    @Autowired
    private UserDetailsService userDetailsService;

    /**
    * User (作者): MRui
    * TODO (描述)：覆盖configure方法
    * Data：2019-01-26 22:29
    */
    @Override
    public void configure(HttpSecurity http) throws Exception {

        //过滤器
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        //AuthenticationManager处理
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //成功处理器Handler
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        //失败处理器Handler
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(failureHandler);

        //Provider
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

        //加入到security框架中（加入到）AuthenticationManager管的Provider集合中
        http.authenticationProvider(smsCodeAuthenticationProvider)
                //将过滤去加到UsernamePasswordAuthenticationFilter后面
            .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
